package pzl.com.library.listener;

import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

import pzl.com.library.chart.BaseChart;

/**
 * @author zl.peng
 * @version [1.0, 2016-11-25]
 */
public abstract class ChartTouchListener extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener {
    public static final String TAG = "ChartTouchListener";
    /**
     * 手势处理器
     */
    protected GestureDetector mGestureDetector;
    protected float mSumScrollX;
    protected float mSumScrollY;

    protected BaseChart mBaseChart;
    protected Scroller mScroller;


    public ChartTouchListener(BaseChart baseChart) {
        mBaseChart = baseChart;
        mGestureDetector = new GestureDetector(mBaseChart.getContext(), this);
        mScroller = new Scroller(mBaseChart.getContext());
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        Log.d(TAG, "onScroll distanceX=" + distanceX + ",distanceY=" + distanceY);
        int mChartScrollType = mBaseChart.getScrollType();
        if (mChartScrollType == BaseChart.SCROLL_TYPE_ENABLE_X || mChartScrollType == BaseChart.SCROLL_TYPE_BOTH_ENABLE)
            mSumScrollX += distanceX;
        if (mChartScrollType == BaseChart.SCROLL_TYPE_ENABLE_Y || mChartScrollType == BaseChart.SCROLL_TYPE_BOTH_ENABLE)
            mSumScrollY += distanceY;

        mBaseChart.onScroll(mSumScrollX, mSumScrollY);
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        Log.d(TAG, "onFling velocityX=" + velocityX + ",velocityY=" + velocityY);
        mScroller.fling((int) mSumScrollX, (int) mSumScrollY, -(int) velocityX, -(int) velocityY, -Integer.MAX_VALUE, Integer.MAX_VALUE, -Integer.MAX_VALUE, Integer.MAX_VALUE);
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mGestureDetector.onTouchEvent(event);
        return true;
    }

    public final void computeScroll() {
        Log.d(TAG, "computeScroll");
        int mChartScrollType = mBaseChart.getScrollType();
        if (mScroller.computeScrollOffset()) {
            if (mChartScrollType == BaseChart.SCROLL_TYPE_ENABLE_X || mChartScrollType == BaseChart.SCROLL_TYPE_BOTH_ENABLE) {
                mSumScrollX = mScroller.getCurrX();
            }
            if (mChartScrollType == BaseChart.SCROLL_TYPE_ENABLE_Y || mChartScrollType == BaseChart.SCROLL_TYPE_BOTH_ENABLE) {
                mSumScrollY = mScroller.getCurrY();
            }
            mBaseChart.onScroll(mSumScrollX, mSumScrollY);
            onFlingAnim();
        }
    }

    /**
     * 正在处于动画fling状态
     */
    protected abstract void onFlingAnim();

}
